"""
static_handler.py - Serve static files from the www/ directory.
Handles MIME types, security checks.
   *** Later will manage session cookies ***
"""

import os
import mimetypes
from urllib.parse import urlparse
import config


def serve(handler):
    # Strip any query string (e.g., ?foo=bar) before mapping to a file path
    parsed = urlparse(handler.path)
    url_path = parsed.path.lstrip('/')
    if url_path == '':
        url_path = 'index.html'          # default page

    file_path = os.path.join(config.PUBLIC_DIR, url_path)

    # Security check: make sure the resolved path is still inside www/
    abs_public = os.path.abspath(config.PUBLIC_DIR)
    abs_file = os.path.abspath(file_path)
    if not abs_file.startswith(abs_public):
        handler.send_error(403, 'Forbidden')
        return

    # If the file doesn't exist, return a 404
    if not os.path.isfile(abs_file):
        handler.send_error(404, 'File Not Found')
        return

    # Guess the MIME type based on the file extension
    mime_type, _ = mimetypes.guess_type(abs_file)
    if mime_type is None:
        mime_type = 'application/octet-stream'

    # Read and serve the file
    try:
        with open(abs_file, 'rb') as f:
            content = f.read()
    except Exception:
        handler.send_error(500, 'Internal Server Error')
        return

    handler.send_response(200)
    handler.send_header('Content-Type', mime_type)
    handler.send_header('Content-Length', len(content))
    handler.end_headers()
    handler.wfile.write(content)